package com.infinitus.activity.web;

import com.infinitus.activity.common.WebConstant;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @create: 2019/1/9
 * @desc:
 */
@Component
@RequestMapping(value = "/api/Attachment/")
public class QiniuController {
    /*****************七牛配置********************/

    @Value("${dfm_qiniu.bucket}")
    private String bucket;
    @Value("${dfm_qiniu.ak}")
    private String AK;
    @Value("${dfm_qiniu.sk}")
    private String SK;
    @RequestMapping(value = "/getUploadToken")
    @ResponseBody
    public Object getUploadToken() {
        Map<String,Object> result=new HashMap<String, Object>();
        try {
            Auth auth = Auth.create(AK, SK);
            String access_token = auth.uploadToken(bucket);
            result.put(WebConstant.RESULT_FILED, WebConstant.SUCCESS);
            result.put(WebConstant.RESULT_DATA, access_token);
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            String strs = sw.toString();
            result.put(WebConstant.RESULT_FILED, WebConstant.FAIL);
            result.put(WebConstant.RESULT_MESSAGE, strs);
        }
        return result;
    }
    @RequestMapping(value = "/getUploadTokenByBucket")
    @ResponseBody
    public Object getUploadToken(String bucket) {
        Map<String,Object> result=new HashMap<String, Object>();
        if(bucket==null||bucket.isEmpty()){
            result.put(WebConstant.RESULT_FILED, WebConstant.FAIL);
            result.put(WebConstant.RESULT_MESSAGE, "bucket不能为空");
            return result;
        }
        try {
            Auth auth = Auth.create(AK, SK);
            String access_token = auth.uploadToken(bucket);
            return "{\"uptoken\":\""+access_token+"\"}";
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            String strs = sw.toString();
            result.put(WebConstant.RESULT_FILED, WebConstant.FAIL);
            result.put(WebConstant.RESULT_MESSAGE, strs);
        }
        return result;
    }
}